//
//  UserAccount.swift
//  SinaWeibo
//
//  Created by 胡阳 on 16/5/24.
//  Copyright © 2016年 young4ever. All rights reserved.
//

import UIKit
import SVProgressHUD

// 在swift2.0中,打印对象需要重写 CustomStringConvertible 协议中的 description 方法
class UserAccount: NSObject ,NSCoding {

    /// 用户授权的唯一票据,用于调用微博的开放接口，同时也是第三方应用验证微博用户登录的唯一票据
    var access_token : String?
    /// access_token的生命周期，单位是秒数
    var expires_in : NSNumber? {
        didSet{ // 只要给expires_in赋值就会调用这个didSet方法
        
            // 根据过期的秒数,生成真正的过期时间
            expires_date = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
            print(expires_date)
        }
    }
    /// access_token过期日期
    var expires_date : NSDate?
    
    /// 授权用户的UID
    var uid : String?
    /// 用户昵称
    var screen_name : String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large : String?
    
    init(dict : [String : AnyObject]) {
        
        super.init()
        setValuesForKeysWithDictionary(dict)
        
//        注意在初始化方法中直接赋值不会调用didSet
//        access_token = dict["access_token"] as? String
//        expires_in = dict["expires_in"] as? NSNumber
//        uid = dict["uid"] as? String
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        print(key)
    }
    
    override var description: String {
        
        let properities = ["access_token", "expires_in", "uid", "expires_date","screen_name", "avatar_large"]
        
        let dict = self.dictionaryWithValuesForKeys(properities)
        
        return "\(dict)"
    }
    
    func loadUserInfo(finished: (account: UserAccount?, error: NSError?)->Void ) {
        
        assert(access_token != nil, "没有授权")
        
        let path = "2/users/show.json"
        let params = ["access_token" : access_token! , "uid" : uid!]
        
        NetworkTools.shareNetworkTools().GET(path, parameters: params, success: { (_, json) in
                print(json)
            //1.判断字典是否有值
            if let dict = json as? [String : AnyObject] {
            
                self.screen_name = dict["screen_name"] as? String
                self.avatar_large = dict["avatar_large"] as? String
                
                finished(account: self, error: nil)
                return
            }
            
            finished(account: nil, error: nil)
            
            }) { (_, error) in
                print(error)
                
                finished(account: nil, error: error)
        }
    }
    
    /**
     返回用户是否登录 
     */
    class func userLogin() -> Bool {
        return UserAccount.loadAccount() != nil
    }
    
    // MARK:- 保存和读取用户信息
    // 保存授权模型
    func saveAccount()
    {
        NSKeyedArchiver.archiveRootObject(self, toFile: "account.plist".cacheDir())
    }
    
    // 加载授权模型
    static var account : UserAccount?
    class func loadAccount() -> UserAccount?
    {
        // 1.判断是否已经加载过模型
        if account != nil {
            return account
        }
        
        // 2.加载模型
        account = NSKeyedUnarchiver.unarchiveObjectWithFile("account.plist".cacheDir()) as? UserAccount
        
        // 3.判断授权是否过期
        if account?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedAscending {
            return nil
        }
        return account
    }
    
    // MARK: - NSCoding协议方法
    // 将对象写入文件
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    // 从文件中读取对象
    required  init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeObjectForKey("expires_in") as? NSNumber
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
}

